package com.example.wan1.view.search;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.wan1.R;
import com.example.wan1.adapter.ArticleListAdapter;
import com.example.wan1.app.MyApplication;
import com.example.wan1.base.activity.SimpleActivity;
import com.example.wan1.dao.HistorySearchDao;
import com.example.wan1.greenDao.db.HistorySearchDaoDao;
import com.example.wan1.model.ArticleBean;
import com.example.wan1.model.SearchHotBean;
import com.example.wan1.model.common.CommonResList;
import com.example.wan1.utils.StatusBarUtil;
import com.example.wan1.utils.ToastUtils;
import com.example.wan1.utils.ToolsUtils;
import com.example.wan1.view.web.WebActivity;
import com.example.wan1.widget.ClearEditText;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;

import org.greenrobot.greendao.query.QueryBuilder;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import mao.com.flexibleflowlayout.TagAdapter;
import mao.com.flexibleflowlayout.TagFlowLayout;

public class SearchActivity extends SimpleActivity implements SearchContract.View, OnLoadMoreListener {

    @BindView(R.id.history_search)
    TagFlowLayout mHistorySearch;
    @BindView(R.id.clear_search_history)
    TextView mClearSearchHistory;
    @BindView(R.id.hot_search)
    TagFlowLayout mHotSearch;
    @BindView(R.id.et_search)
    ClearEditText mEtSearch;
    @BindView(R.id.cancel_search)
    TextView mCancelSearch;
    @BindView(R.id.search_rv)
    RecyclerView mSearchRv;
    @BindView(R.id.search_header)
    LinearLayout mSearchHeader;
    @BindView(R.id.search_refresh)
    SmartRefreshLayout mSearchRefresh;
    @BindView(R.id.search_id)
    LinearLayout mToolbar;

    @Inject
    SearchPresenter mPresenter;
    @Inject
    ArticleListAdapter mAdapter;
    @Inject
    List<ArticleBean> mList;

    private List<SearchHotBean> mHotList;
    private List<String> mTitleList;
    private int page = 0;
    private List<HistorySearchDao> mHistorySearchDaos;
    private TagAdapter mTagAdapter;

    private String type = "normal";
    private int id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);

        if (!TextUtils.isEmpty(getIntent().getStringExtra("type"))) {
            id = getIntent().getIntExtra("id", -1);
            type = getIntent().getStringExtra("type");
        }
    }

    @Override
    public void initView() {
        //mAdapter = new ArticleListAdapter(R.layout.article_item, mList);
        mSearchRv.setAdapter(mAdapter);
        mSearchRv.setLayoutManager(new LinearLayoutManager(this));

        mCancelSearch.setOnClickListener(v -> finish());

        mEtSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() == 0) {
                    mSearchRefresh.setVisibility(View.GONE);
                    mSearchHeader.setVisibility(View.VISIBLE);
                    page = 0;
                    //倒序
                    QueryBuilder<HistorySearchDao> builder = MyApplication.getDaoSession().queryBuilder(HistorySearchDao.class);
                    mHistorySearchDaos = builder.orderDesc(HistorySearchDaoDao.Properties.Id).list();
                    mTagAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        mEtSearch.setOnEditorActionListener((v, actionId, event) -> {
            Log.i("zxd", "Action: " + actionId);
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                hideSoftKeyboard(SearchActivity.this);
                Log.i("zxd", "onEditorAction: " + mEtSearch.getText().toString());
                page = 0;
                doSearch(mEtSearch.getText().toString());
                mSearchRefresh.setVisibility(View.VISIBLE);
                mSearchHeader.setVisibility(View.GONE);

                mSearchRv.scrollToPosition(0);

                //插入本地sqlite数据库，需要判断数据库中是否存在这个搜索历史，如果有就不插入，没有就插入
                HistorySearchDao dao = new HistorySearchDao();
                dao.setHistory(mEtSearch.getText().toString());

                QueryBuilder<HistorySearchDao> builder = MyApplication.getDaoSession().queryBuilder(HistorySearchDao.class);
                builder.where(HistorySearchDaoDao.Properties.History.eq(mEtSearch.getText().toString()))
                        .orderAsc(HistorySearchDaoDao.Properties.History);
                List<HistorySearchDao> daoList = builder.list(); //查出当前对应的数据
                if (daoList.size() == 0) {
                    MyApplication.getDaoSession().insert(dao);
                } else {
                    MyApplication.getDaoSession().delete(daoList.get(0));
                    MyApplication.getDaoSession().insert(dao);
                }
            }
            return false;
        });

        mSearchRefresh.setEnableRefresh(false);
        //搜索历史
        mTagAdapter = new TagAdapter() {
            @Override
            public int getItemCount() {
                return mHistorySearchDaos.size();
            }

            @Override
            public View createView(LayoutInflater inflater, ViewGroup parent, int position) {
                return inflater.inflate(R.layout.website_item, parent, false);
            }

            @Override
            public void bindView(View view, final int position) {
                TextView tv = view.findViewById(R.id.website_tv);
                tv.setText(mHistorySearchDaos.get(position).getHistory());
                if (position % 3 == 0) {
                    tv.setBackground(getDrawable(R.drawable.tag_one));
                } else if (position % 3 == 1) {
                    tv.setBackground(getDrawable(R.drawable.tag_two));
                } else {
                    tv.setBackground(getDrawable(R.drawable.tag_three));
                }
            }

            @Override
            public void onTagItemViewClick(View v, final int position) {
                super.onTagItemViewClick(v, position);
                switch (v.getId()) {
                    case R.id.website_tv:
                        //给EditText赋值
                        mEtSearch.setText(mHistorySearchDaos.get(position).getHistory());
                        mSearchRefresh.setVisibility(View.VISIBLE);
                        mSearchHeader.setVisibility(View.GONE);
                        page = 0;
                        //同时进行网络请求
                        doSearch(mEtSearch.getText().toString());
                        hideSoftKeyboard(SearchActivity.this);
                        //点历史数据不需要插入数据
                        mSearchRv.scrollToPosition(0);

                        HistorySearchDao dao = new HistorySearchDao();
                        dao.setHistory(mEtSearch.getText().toString());

                        QueryBuilder<HistorySearchDao> builder = MyApplication.getDaoSession().queryBuilder(HistorySearchDao.class);
                        builder.where(HistorySearchDaoDao.Properties.History.eq(mEtSearch.getText().toString()))
                                .orderAsc(HistorySearchDaoDao.Properties.History);
                        List<HistorySearchDao> daoList = builder.list(); //查出当前对应的数据
                        if (daoList.size() == 0) {
                            MyApplication.getDaoSession().insert(dao);
                        } else {
                            MyApplication.getDaoSession().delete(daoList.get(0));
                            MyApplication.getDaoSession().insert(dao);
                        }

                        break;
                }
            }
        };
        mHistorySearch.setAdapter(mTagAdapter);
        //清空历史
        mClearSearchHistory.setOnClickListener(v -> {
            MyApplication.getDaoSession().deleteAll(HistorySearchDao.class);
            mHistorySearchDaos.clear();
            mTagAdapter.notifyDataSetChanged();
        });
        //点击进入Web界面
        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            Intent intent = new Intent(SearchActivity.this, WebActivity.class);
            intent.putExtra("url", mAdapter.getData().get(position).getLink());
            intent.putExtra("title", mAdapter.getData().get(position).getTitle());
            startActivity(intent);
        });

        mSearchRefresh.setOnLoadMoreListener(this);

        int color = ToolsUtils.getThemeColor(this);
        if (color != 0) {
            mToolbar.setBackgroundColor(color);
            StatusBarUtil.setColor(this, color, 0);
        }
        if (ToolsUtils.getNightMode(this))
            StatusBarUtil.setTransparent(this);
    }

    @Override
    protected int initLayoutId() {
        return R.layout.activity_search;
    }

    @Override
    public void initData() {
        mHotList = new ArrayList<>();
        mTitleList = new ArrayList<>();
        //mList = new ArrayList<>();
        QueryBuilder<HistorySearchDao> builder = MyApplication.getDaoSession().queryBuilder(HistorySearchDao.class);
        mHistorySearchDaos = builder.orderDesc(HistorySearchDaoDao.Properties.Id).list();

        mPresenter.searchHotData();//查找搜索热词
        /*if ("wx".equals(type)) {
            mPresenter.searchByWechat(id, page, mEtSearch.getText().toString());
        } else if ("knowledge".equals(type)) {
            mPresenter.searchByKnowledge(page, mEtSearch.getText().toString());
        } else {
            //normal
            mPresenter.search(page, mEtSearch.getText().toString());
        }*/
    }

    private void doSearch(String content) {
        if ("normal".equals(type)) {
            mPresenter.search(page, content);
        } else if ("wx".equals(type)) {
            if (page == 0)
                page = 1;
            mPresenter.searchByWechat(id, page, content);
        } else if ("knowledge".equals(type)) {
            mPresenter.searchByKnowledge(page, content);
        }
    }

    /**
     * 隐藏软键盘(只适用于Activity，不适用于Fragment)
     */
    public static void hideSoftKeyboard(Activity activity) {
        View view = activity.getCurrentFocus();
        if (view != null) {
            InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    @Override
    public void onSuccess(CommonResList<ArticleBean> data) {
        if ("wx".equals(type)) {
            if (page == 0)
                page = 1;
            if (page == 1) {
                mList.clear();
            } else {
                mSearchRefresh.finishLoadMore(true);
            }
            //mList.addAll(data.getDatas());
            mAdapter.addData(data.getDatas());
            mAdapter.notifyDataSetChanged();
            page = data.getCurPage() + 1;
            if (data.getDatas().size() == 0) {
                Toast.makeText(SearchActivity.this, "真的没有了!", Toast.LENGTH_SHORT).show();
            }
        } else if ("knowledge".equals(type)) {
            if (page == 0) {
                mList.clear();
            } else {
                mSearchRefresh.finishLoadMore(true);
            }
            //mList.addAll(data.getDatas());
            mAdapter.addData(data.getDatas());
            mAdapter.notifyDataSetChanged();
            page = data.getCurPage();
            if (data.getDatas().size() == 0) {
                Toast.makeText(SearchActivity.this, "真的没有了!", Toast.LENGTH_SHORT).show();
            }
        } else {
            //normal
            if (page == 0) {
                mList.clear();
            } else {
                mSearchRefresh.finishLoadMore(true);
            }
            //mList.addAll(data.getDatas());
            mAdapter.addData(data.getDatas());
            mAdapter.notifyDataSetChanged();
            page = data.getCurPage();

            if (data.getDatas().size() == 0) {
                Toast.makeText(SearchActivity.this, "真的没有了!", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onFailure(String msg) {
        ToastUtils.showToast(msg);
    }

    @Override
    public void onGetHotData(List<SearchHotBean> data) {
        mHotList.addAll(data);

        for (int i = 0; i < data.size(); i++) {
            mTitleList.add(data.get(i).getName());
        }

        mHotSearch.setAdapter(new TagAdapter() {
            @Override
            public int getItemCount() {
                return mTitleList.size();
            }

            @Override
            public View createView(LayoutInflater inflater, ViewGroup parent, int position) {
                return inflater.inflate(R.layout.website_item, parent, false);
            }

            @Override
            public void bindView(View view, final int position) {
                TextView tv = view.findViewById(R.id.website_tv);
                tv.setText(mTitleList.get(position));
                if (position % 3 == 0) {
                    tv.setBackground(getDrawable(R.drawable.tag_one));
                } else if (position % 3 == 1) {
                    tv.setBackground(getDrawable(R.drawable.tag_two));
                } else {
                    tv.setBackground(getDrawable(R.drawable.tag_three));
                }
            }

            @Override
            public void onTagItemViewClick(View v, final int position) {
                super.onTagItemViewClick(v, position);
                switch (v.getId()) {
                    case R.id.website_tv:
                        //给EditText赋值
                        mEtSearch.setText(mTitleList.get(position));
                        mSearchRefresh.setVisibility(View.VISIBLE);
                        mSearchHeader.setVisibility(View.GONE);
                        mSearchRv.scrollToPosition(0);
                        page = 0;
                        //同时进行网络请求
                        doSearch(mTitleList.get(position));
                        hideSoftKeyboard(SearchActivity.this);
                        //插入本地sqlite数据库，先判断有没有这个历史，没有才能插入
                        HistorySearchDao dao = new HistorySearchDao();
                        dao.setHistory(mTitleList.get(position));

                        if (mHistorySearchDaos.size() == 0) {
                            MyApplication.getDaoSession().insert(dao);
                        } else {
                            QueryBuilder<HistorySearchDao> builder = MyApplication.getDaoSession().queryBuilder(HistorySearchDao.class);
                            builder.where(HistorySearchDaoDao.Properties.History.eq(mEtSearch.getText().toString()))
                                    .orderAsc(HistorySearchDaoDao.Properties.History);
                            List<HistorySearchDao> daoList = builder.list(); //查出当前对应的数据
                            if (daoList.size() == 0) {
                                MyApplication.getDaoSession().insert(dao);
                            } else {
                                MyApplication.getDaoSession().delete(daoList.get(0));
                                MyApplication.getDaoSession().insert(dao);
                            }
                        }
                        break;
                }
            }

            @Override
            public void onItemSelected(View v, final int position) {
                super.onItemSelected(v, position);
            }

        });
        mHotSearch.onDataChanged();
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        mSearchRv.postDelayed(() -> {
            doSearch(mEtSearch.getText().toString());
            mSearchRefresh.finishLoadMore();
        }, 200);
    }
}
